﻿var NewsModel = require("./js/news");
var formidable = require('formidable');
var fs = require("fs");

module.exports = {

    render: function(req, res) {

        var news = global.news,
            pageNum = 10,
            page = (req.params.page || 1) - 1,
            startIndex = page * pageNum,
            endIndex = startIndex + pageNum;

        res.render('admin/news', {
            layout: 'admin',
            xwActive: 'active',
            news: news.slice(startIndex, endIndex),
            pageIndex: page + 1,
            totalCount: Math.ceil(news.length / pageNum)
        });
    },

    renderDetail: function(req, res) {

        var newsID = req.params.id || "",
            page = req.params.page || 1;
        res.render('admin/newsDetail', {
            layout: 'admin',
            xwActive: 'active',
            newsID: newsID,
            page: page
        });
    },

    uploadimage: function(req, res, next) {

        var img_url = '/lib/ueditor/images/ueditor/';
        if (req.query.action === 'uploadimage') {
            res.ue_up(img_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
        } else {
            res.setHeader('Content-Type', 'application/json');
            res.redirect('/lib/ueditor/ueditor/nodejs/config.json');
        }
    },

    //添加新闻
    add: function(req, res, next) {

        operateNews("add", req, res);
    },
    //删除新闻
    dels: function(req, res, next) {

        var newsModel = new NewsModel();
        newsModel.dels(req.body.ids, function(data) {
            res.json(data);
        });
    },
    //编辑新闻
    edit: function(req, res, next) {

        operateNews("edit", req, res);
    },
    //查询新闻
    select: function(req, res, next) {

        var newsModel = new NewsModel();
        res.json(newsModel.select(req.query.id));
    }
};

function operateNews(oType, req, res) {

    var form = new formidable.IncomingForm();
    form.uploadDir = './modules/admin/news/uploadImg/';
    form.parse(req, function(err, fields, files) {

        if (err) return res.redirect(303, '/error');
        var imgUrl;
        if (files.upload.name) {
            var imgName = Math.ceil(Math.random() * 1000000000) + files.upload.name;
            fs.renameSync(files.upload.path, form.uploadDir + imgName);
            imgUrl = "/admin/news/uploadImg/" + imgName;
        }

        var newsModel = new NewsModel(fields.title, fields.author, fields.source, fields.sourceUrl, imgUrl, fields.introduce, fields.content);
        if (fields.id)
            newsModel.edit(fields.id, function(data) {
                res.redirect('/admin/news/' + fields.page);
            });
        else
            newsModel.add(function(data) {
                res.redirect('/admin/news/1');
            });

    });
}